//引入pinia
import { defineStore } from 'pinia'
import {login} from '@/api/login'
import { ElMessage } from 'element-plus'
import {ref} from 'vue'

//创建store
export const useUserStore = defineStore('localUser', () => {
    // 定义管理用户数据的state
    const user = ref({})
    const token=ref({})
    const isLogin=ref(false)

    // 定义获取接口数据的action函数
    const userLogin = async (account: String,password: String) => {
        //执行登录
        const result = await login({'userName':account,'password':password}) as any
        //登录成功
        if(result.code==200){
            user.value={
                userName:result.data.userName,
                account:result.data.account,
                roles:result.data.roles
            },
            isLogin.value=true as boolean;
            token.value=result.token

            //信息提示
            ElMessage({
                showClose: true,
                message: result.msg,
                type: 'success',
            })
        }else{
            //登录失败，提示错误信息
            ElMessage({
                showClose: true,
                message: result.msg,
                type: 'error',
            })
        }
    }

    //登出方法
    const userLoginOut = () => {
        user.value={
            userName:'',
            account:'',
            roles:[]
        },
        isLogin.value=false as boolean;
        token.value=null as any;
    }

    // 以对象形式把state和action return
    return {user, userLogin,userLoginOut,token,isLogin}
},
//持久化配置
{
    persist: true,
}
)